package cn.project.engineering.utils

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import java.util.*


/**
 *
 * @author  lifuhai
 * @date 2021/2/20 15:20
 */
class AlarmManagerUtil {
    companion object {
        const val SCREEN_CONTROL_ACTION = "cn.project.engineering.screen.control"

        fun setAlarmTime(context: Context, timeInMillis: Long, intent: Intent) {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val sender = PendingIntent.getBroadcast(context, intent.getIntExtra("id", 0), intent, PendingIntent.FLAG_CANCEL_CURRENT)
            val interval = intent.getLongExtra("intervalMillis", 0)

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeInMillis, sender)
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, sender)
            }
        }

        /**
         * 设置闹钟
         *
         * @param context 上下文
         * @param flag 周期性时间间隔的标志,flag = 0 表示一次性的闹钟, flag = 1 表示每天提醒的闹钟(1天的时间间隔), flag = 2 表示按周每周提醒的闹钟（一周的周期性时间间隔）
         * @param hour 时
         * @param minute 分
         * @param id 闹钟id
         * @param week  0表示一次性闹钟或者按天的周期性闹钟，非0 的情况下是几就代表以周为周期性的周几的闹钟
         * @param tips 闹钟提示信息
         */
        fun setAlarm(context: Context, flag: Int, hour: Int, minute: Int, id: Int, week: Int, tips: String) {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val calendar = Calendar.getInstance()
            var intervalMillis: Long = 0
            calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), hour, minute, 0)
            when (flag) {
                0 -> {
                    intervalMillis = 0
                }
                1 -> {
                    intervalMillis = 24 * 3600 * 1000
                }
                2 -> {
                    intervalMillis = 24 * 3600 * 1000 * 7
                }
            }
            val intent = Intent(SCREEN_CONTROL_ACTION)
            intent.putExtra("intervalMillis", intervalMillis)
            intent.putExtra("id", id)
            intent.putExtra("msg", tips)
            val sender = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_CANCEL_CURRENT)

            when {
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
                    alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.timeInMillis), sender)
                }
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT -> {
                    alarmManager.setExact(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.timeInMillis), sender)
                }
                else -> {
                    when (flag) {
                        0 -> {
                            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, sender)
                        }
                        else -> {
                            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calMethod(week, calendar.timeInMillis), intervalMillis, sender)
                        }
                    }
                }
            }
        }

        /**
         * 取消闹钟
         *
         * @param context 上下文
         * @param action 闹钟广播action
         * @param id 闹钟id
         */
        fun cancelAlarm(context: Context, action: String, id: Int) {
            val intent = Intent(action)
            val pi = PendingIntent.getBroadcast(context, id, intent, PendingIntent.FLAG_CANCEL_CURRENT)
            val am = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            am.cancel(pi)
        }

        /**
         * @param weekFlag 是周几
         * @param dateTime 时间戳
         * @return 返回起始闹钟时间的时间戳
         */
        private fun calMethod(weekFlag: Int, dateTime: Long): Long {
            var time: Long = 0
            when (weekFlag) {
                0 -> {
                    time = if (dateTime > System.currentTimeMillis()) {
                        dateTime
                    } else {
                        dateTime + 24 * 3600 * 1000
                    }
                }
                else -> {
                    val calendar = Calendar.getInstance()
                    var week = calendar.get(Calendar.DAY_OF_WEEK)
                    when (week) {
                        1 -> {
                            week = 7
                        }
                        2 -> {
                            week = 1
                        }
                        3 -> {
                            week = 2
                        }
                        4 -> {
                            week = 3
                        }
                        5 -> {
                            week = 4
                        }
                        6 -> {
                            week = 5
                        }
                        7 -> {
                            week = 6
                        }
                    }

                    if (weekFlag == week) {
                        if (dateTime > System.currentTimeMillis()) {
                            time = dateTime
                        } else {
                            time = dateTime + 7 * 24 * 3600 * 1000
                        }
                    } else if (weekFlag > week) {
                        time = dateTime + (weekFlag - week) * 24 * 3600 * 1000
                    } else if (weekFlag < week) {
                        time = dateTime + (weekFlag - week + 7) * 24 * 3600 * 1000
                    }
                }
            }

            return time
        }
    }
}